﻿using System;
using System.Windows.Forms;

namespace DevelopersTestPad.AppFrame
{
    internal sealed class WorkerScope : IDisposable
    {
        private static int Index { set; get; }

        /// <summary>
        /// No public constructor available.
        /// </summary>
        private WorkerScope()
        {            
        }

        /// <summary>
        /// Creates a new WorkerScope.
        /// </summary>
        /// <returns>WorkerScope</returns>
        internal static WorkerScope CreateNew()
        {
            WorkerScope scope = new WorkerScope();
            SetCursor(Cursors.WaitCursor);
            Index++;
            return scope;
        }

        private static void SetCursor(Cursor newCursor)
        {
            if (AppContext.Current.MainWindow.InvokeRequired)
            {
                AppContext.Current.MainWindow.BeginInvoke(new SetCursorDelegate(SetCursorImpl), newCursor);
            }
            else
            {
                SetCursorImpl(newCursor);
            }            
        }
       

        private static void SetCursorImpl(Cursor newCursor)
        {
            AppContext.Current.MainWindow.Cursor = newCursor;
        }

        delegate void SetCursorDelegate(Cursor newCursor);

        void IDisposable.Dispose()
        {
            Index--;

            if (Index == 0)
            {
                SetCursor(Cursors.Default);
            }
        }
    }
}
